package com.atguigu.gmall.product.component;


import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * 进行文件上传的组件
 */
@Data
@EnableConfigurationProperties(MinioProperties.class)
//1、MinioProperties的属性绑定生效   2、MinioProperties 放在容器中
@Configuration
public class MinioService {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 容器中放一个操作minio的客户端
     * @return
     */


    @Bean
    MinioClient minioClient() throws Exception {
        MinioClient minioClient = new MinioClient(
                minioProperties.getEndpoint(),
                minioProperties.getAccessKey(),
                minioProperties.getSecretKey());
        //判断默认用的桶有没有
        if(!minioClient.bucketExists(minioProperties.getBucketName())){
            minioClient.makeBucket(minioProperties.getBucketName());
        }
        //The difference between the request time and the server's time is too large；重启minio
        return minioClient;
    }


    /**
     * 上传文件
     * @param file
     * @return
     */
    public String uploadFile(MultipartFile file) throws Exception {
        //String bucketName, String objectName, InputStream stream, PutObjectOptions options
        //1、文件名
        String filename = UUID.randomUUID().toString() +"_"+ file.getOriginalFilename();

        //2、真正的文件流
        InputStream inputStream = file.getInputStream();

        //3、上传的设置项
        PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1);
        //设置上内容类型
        options.setContentType(file.getContentType());

        minioClient.putObject(minioProperties.getBucketName(),filename,inputStream,options);


        //4、返回可访问的路径
        String path = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + filename;
        return path;
    }

    public String uploadFile(InputStream file) {

        return "";
    }


}
